package com.shareyi.wox.result;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.context.Context;

import com.shareyi.wox.context.ActionContext;
import com.shareyi.wox.context.ServletActionContext;
import com.shareyi.wox.context.ValueContext;
import com.shareyi.wox.core.ActionInvocation;
import com.shareyi.fileutil.FileUtil;
import com.shareyi.simpleserver.core.HttpRequest;
import com.shareyi.simpleserver.core.HttpResponse;

public class VelocityLayoutResult extends VelocityResult {

	
	
	public static String KEY_SCREEN_CONTENT = "screen_content";
	public static String KEY_EXCEPTION = "exception";
	public static String KEY_LAYOUT = "layout";
	protected String defaultLayout="default.vm";
	protected String errorTemplate;
	protected String layoutDir="/vm/layout/";
	protected String inputEncoding="utf-8";
	protected String outputEncoding="utf-8";

	private Map<String, Object> velocityTools;
	
	@Override
	protected void doExecute(String finalLocation, ActionInvocation invocation)
			throws Exception {
		try {
			doIt(finalLocation, invocation, null);
		}
		catch (Exception e) {
		}
	}

	private void doIt(String finalLocation, ActionInvocation invocation,
			Throwable  exception) throws Exception {
		
		if(!initialed){
			init();
			initialed=true;
		}
		
		  ValueContext valueContext = ActionContext.getContext().getValueContext();
	        HttpRequest request = ServletActionContext.getRequest();
	        HttpResponse response = ServletActionContext.getResponse();
	        try {
	            Template t = super.getTemplate(invocation, finalLocation);

	            Context context = createContext(valueContext, request, response, finalLocation);
	            if (exception != null) {
					context.put(KEY_EXCEPTION, exception);
				}
	            StringWriter stringWriter = new StringWriter();
				t.merge(context, stringWriter);
				
				context.put(KEY_SCREEN_CONTENT, stringWriter.toString());
				Object obj = context.get(KEY_LAYOUT);
				String layout = (obj == null) ? null : obj.toString();
				if (layout == null) {
					layout =FileUtil.contactPath(layoutDir, defaultLayout);
				}
				else {
					layout = FileUtil.contactPath(layoutDir, layout);
				}
				
				Template layoutVm = null;
				try {
					layoutVm = super.getTemplate( invocation, layout);
				}
				catch (Exception e) {
					
				}
			//	String encoding="utf-8";
				Writer writer =  response.getPrintWriter();
				layoutVm.merge(context, writer);
				writer.flush();
	        } catch (Exception e) {
	            throw e;
	        } finally {
	           
	        }
		
	}
	
}
